#include "client.h"

namespace srpc
{
    void TcpRpcChannelClient::Close()
    {
        ::close(mFd);
    }

    int TcpRpcChannelClient::Start()
    {
        return 0;
    }

    int TcpRpcChannelClient::constructConnection()
    {
        mFd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (-1 == mFd)
        {
            std::cout << "socket error" << std::endl;
            return -1;
        }

        sockaddr_in ServerAddress;
        memset(&ServerAddress, 0, sizeof(sockaddr_in));
        ServerAddress.sin_family = AF_INET;
        if (::inet_pton(AF_INET, mServerIP.c_str(), &ServerAddress.sin_addr) != 1)
        {
            std::cout << "inet_pton error" << std::endl;
            ::close(mFd);
            return -1;
        }

        ServerAddress.sin_port = htons(mServerPort);

        if (::connect(mFd, (sockaddr *)&ServerAddress, sizeof(ServerAddress)) == -1)
        {
            std::cout << "connect error" << std::endl;
            ::close(mFd);
            return -1;
        }
        return 0;
    }

    int TcpRpcChannelClient::OpenChannel(std::string address, TcpRpcChannel *tcpRpcChannel)
    {
        int sep = address.find(':');
        if (sep < 0)
        {
            std::cout << "invalid address" << std::endl;
            return 1;
        }
        mServerIP = address.substr(0, sep);
        mServerPort = stoi(address.substr(sep + 1, address.size()));
        if (constructConnection() != 0)
        { 
            std::cout << "connect to " << address << "failed" << std::endl;
            return 1;
        }
        tcpRpcChannel->SetBufferEvent(mFd, mpEvBase);
        return 0;
    }
} // namespace srpc